﻿Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Module SecurityHelper
    Private ReadOnly EncryptionKey As String = "20252025202520252025202520252025" '密钥
    Private ReadOnly IV As String = "0312031203120312"  '初始化向量

    Public Function EncryptString(plainText As String) As String '加密
        Using aesAlg = Aes.Create()
            aesAlg.Key = Encoding.ASCII.GetBytes(EncryptionKey)
            aesAlg.IV = Encoding.ASCII.GetBytes(IV)
            aesAlg.Mode = CipherMode.CBC     ' 显式设置模式 
            aesAlg.Padding = PaddingMode.PKCS7  ' 显式设置填充 

            Using encryptor = aesAlg.CreateEncryptor()
                Using msEncrypt As New MemoryStream()
                    Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                        Using swEncrypt As New StreamWriter(csEncrypt)
                            swEncrypt.Write(plainText)
                        End Using
                    End Using
                    Return Convert.ToBase64String(msEncrypt.ToArray())
                End Using
            End Using
        End Using
    End Function

    Public Function DecryptString(cipherText As String) As String '解密
        Using aesAlg = Aes.Create()
            aesAlg.Key = Encoding.ASCII.GetBytes(EncryptionKey)
            aesAlg.IV = Encoding.ASCII.GetBytes(IV)
            aesAlg.Mode = CipherMode.CBC
            aesAlg.Padding = PaddingMode.PKCS7

            Using decryptor = aesAlg.CreateDecryptor()
                Using msDecrypt As New MemoryStream(Convert.FromBase64String(cipherText))
                    Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
                        Using srDecrypt As New StreamReader(csDecrypt)
                            Return srDecrypt.ReadToEnd()
                        End Using
                    End Using
                End Using
            End Using
        End Using
    End Function
End Module